package cn.fly.identification.service.Impl;

import cn.fly.identification.service.IdentificationService;
import cn.fly.identification.utils.DetectionUtils;
import cn.fly.identification.utils.IdentificationUtils;
import cn.fly.identification.utils.LivingUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import java.util.concurrent.atomic.AtomicBoolean;



@Service
public class IdentificationServiceImpl implements IdentificationService {

    private static final Double SPOOFING_THRESHOLD = 0.00048;
    private static final Double FACE_LIVENESS_THRESHOLD = 0.3;
    private static final Double FACE_SOCRE = 95.1578;
    private static final String APP_ID = "57979629";
    private static final String API_KEY = "MFe6CBtNduYQlLpBIpD2xqbv";
    private static final String SECRET_KEY = "WziOM0ihigLifhtn1jrR3LkOVzvZJokN";


    @Override
    public AtomicBoolean checkDete(String baseImg) {
        String deteString = DetectionUtils.faceDetect(baseImg);

        JSONObject deteJson = new JSONObject(deteString);

        System.out.println("deteJson=>" + deteJson);

        if (!deteJson.get("error_msg").equals("SUCCESS"))
            return new AtomicBoolean(false);

        //Double faceLiveness = deteJson.getJSONObject("result").getDouble("face_liveness");

        Double spoofing = deteJson.getJSONObject("result").getJSONArray("face_list").getJSONObject(0).getDouble("spoofing");

        System.out.println(spoofing);

        if (spoofing < SPOOFING_THRESHOLD)
            return new AtomicBoolean(true);
        else
            return new AtomicBoolean(false);

    }

    @Override
    public AtomicBoolean checkLiving(String baseImg) {
        String livingString = LivingUtils.faceVerify(baseImg);

        System.out.println("livingString = >" + livingString);

        JSONObject livingJson = new JSONObject(livingString);

        if (!livingJson.get("error_msg").equals("SUCCESS"))
            return new AtomicBoolean(false);

        System.out.println("livingJson=>" + livingJson);

        Double faceLiveness = livingJson.getJSONObject("result").getDouble("face_liveness");

        Double spoofing = livingJson.getJSONObject("result").getJSONArray("face_list").getJSONObject(0).getDouble("spoofing");

        System.out.println(faceLiveness);
        System.out.println(spoofing);

        if (spoofing < SPOOFING_THRESHOLD && faceLiveness > FACE_LIVENESS_THRESHOLD)
            return new AtomicBoolean(true);
        else
            return new AtomicBoolean(false);
    }

    @Override
    public AtomicBoolean identify(String baseImg) {
        System.out.println("开始人脸识别");

        Double score = IdentificationUtils.login(baseImg, APP_ID, API_KEY, SECRET_KEY);

        System.out.println("人脸识别得分" + score);

        if (score > FACE_SOCRE)
            return new AtomicBoolean(true);
        else
            return new AtomicBoolean(false);
    }
}
